package org.jskomment.server;

import javax.servlet.http.*;

import com.google.appengine.api.utils.SystemProperty;

import java.io.*;

/** serves JQuery and jskomment in a single run- */
public class EmbedServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  /** gets the map corresponding to  {@code req.getParameter(Constants.KEY)} */
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		res.setContentType("text/javascript");
		res.getWriter().write("/** This is the main jskomment script\n It embeds jquery, swfobject.js and json2.js.\n */ \n\n\n");
		
		res.getWriter().write("\n if (window.jQuery === undefined) { \n");
		BufferedReader jquery = new BufferedReader(new FileReader("jquery-1.5.1.min.js"));
		String s;
		while ((s = jquery.readLine()) !=null) {
			res.getWriter().write(s+"\n");
		}
		jquery.close();
		res.getWriter().write("\n}\n");

		res.getWriter().write("\n if (window.swfobject === undefined) { \n");
		BufferedReader swfcomment = new BufferedReader(new FileReader("swfobject.js"));
		while ((s = swfcomment.readLine()) !=null) {
			res.getWriter().write(s+"\n");
		}
		swfcomment.close();
		res.getWriter().write("\n}\n");
    
		BufferedReader json2_js = new BufferedReader(new FileReader("json2.js"));
		while ((s = json2_js.readLine()) !=null) {
			res.getWriter().write(s+"\n");
		}
		json2_js.close();

    BufferedReader jskomment_js = new BufferedReader(new FileReader("jskomment-core.js"));
    while ((s = jskomment_js.readLine()) !=null) {
      res.getWriter().write(s+"\n");
    }
    jskomment_js.close();

    // changing the url at development time
    if (SystemProperty.environment.value().equals(SystemProperty.Environment.Value.Development)) {
      res.getWriter().write("JSKOMMENT.url = 'http://localhost:8888';\n");      
    }
    
    res.getWriter().write("JSKOMMENT.main();\n");
	}
}
